import { Injectable } from '@angular/core';

/*
  Generated class for the StorageProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class StorageProvider {

  constructor() {
    console.log('Hello StorageProvider Provider');
  }

  write(key:string, value:any) {
    if (value) {
      value = JSON.stringify(value);//将value对象转换成字符串
    }
    localStorage.setItem(key, value);
  }

  read(key:string) {
    let value = localStorage.getItem(key);
    if (value && value != "undefined" && value != "null") {
      return JSON.parse(value);//如果有值则返回value对象
    }
    return null;//没有值则返回空
  }

  //一旦删除，key对应的数据将会全部删除
  remove(key:string) {
    localStorage.removeItem(key);
  }
  //全部清除：localStorage.clear(); 某些时候使用removeItem逐个删除太麻烦，可以使用clear,执行的后果是会清除所有localStorage对象保存的数据
  clearAll() {
    localStorage.clear();
  }

  getLength(){
    console.log(localStorage.length);
    for(var i=0;i<localStorage.length;i++){

      var name = localStorage.key(i)​;
      console.log(name);
      var value = localStorage.getItem(name);​
      console.log(value);

    }
    return localStorage.length;
  }

  //存过期时间的方法
  setForExp(key, value) {
    var curTime = new Date().getTime();
    localStorage.setItem(key, JSON.stringify({ data: value, time: curTime }));
  }

  //指定过期时间的get方法;1000*60:过期时间为1分钟
  getWithExp(key, exp) {
    var data = localStorage.getItem(key);
    var dataObj = JSON.parse(data);
    if (new Date().getTime() - dataObj.time > exp) {
      console.log('信息已过期');
    } else {
      var dataObjDatatoJson = JSON.parse(dataObj.data)
      return dataObjDatatoJson;
    }
  }

}
